<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Modules\Blog\Service;


use App\Models\Blog\Article;
use App\Models\Blog\Message;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ArticleService
{

    use Service;

    /**
     * 获取文章
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleLimitService( $request )
    {
        $user    = $this->getCommon()->UserCommonService();
        $where   = function ( $query ) use ( $user ) {
            $query->where('user_id', $user->id);
            $query->where('is_show', 1);
            $query->where('status', 3);
            $query->where('static', 1);
        };
        $select  = [ 'id', 'user_id', 'is_show', 'title', 'browse', 'share', 'like', 'step', 'comment', 'root' ];
        $article = Article::AllModel($where, [], $select, (int) config('blog_page.ARTICLE_LIMIT'), 'created_at', 'desc');
        return data($article);
    }

    /**
     * 删除文章
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleDestroyService( $id )
    {
        $user  = $this->getCommon()->UserCommonService();
        $where = function ( $query ) use ( $id, $user ) {
            $query->where('user_id', $user->id);
            if ( ! is_array($id) ) $query->where('id', $id);
            else $query->whereIn('id', $id);
        };
        Article::UpdateModel($where, [
            'static'     => 2,
            'deleted_at' => Carbon::now()->toDateTimeString(),
        ]);
        return data(NULL, $this->getErrorCode()::message(204));
    }

    /**
     * 查询所有文章得评论、点赞、踩、分享数量
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleDetailsService( $request )
    {
        $user              = $this->getCommon()->UserCommonService();
        $where             = function ( $query ) use ( $user, $request ) {
            if ( $request->filled('id') ) $query->where('id', $request->input('id'));
            $query->where('user_id', $user->id);
        };
        $data[ 'step' ]    = Article::SumModel($where, [], 'step');
        $data[ 'like' ]    = Article::SumModel($where, [], 'like');
        $data[ 'share' ]   = Article::SumModel($where, [], 'share');
        $data[ 'comment' ] = Article::SumModel($where, [], 'comment');
        return data($data);
    }

    /**
     * 获取文章图表信息
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleEchartService( $request )
    {
        $user  = $this->getCommon()->UserCommonService();
        $start = Carbon::now()->startOfWeek()->timestamp;
        $data  = [];
        for ( $i = 0; $i < 7; $i++ ) {
            $s                   = date('Y-m-d H:i:s', strtotime("+" . $i . " day", $start));
            $e                   = date('Y-m-d H:i:s', strtotime("+" . ( $i + 1 ) . " day", $start));
            $data[ 'article' ][] = Article::BetweenCountModel($s, $e, [
                'user_id' => $user->id, 'static' => 1, 'status' => 3,
            ]);
            $data[ 'share' ][]   = Message::BetweenCountModel($s, $e, [ 'p_user_id' => $user->id, 'is_show' => 1 ]);
            $data[ 'like' ][]    = Message::BetweenCountModel($s, $e, [ 'p_user_id' => $user->id, 'is_show' => 2 ]);
            $data[ 'step' ][]    = Message::BetweenCountModel($s, $e, [ 'p_user_id' => $user->id, 'is_show' => 3 ]);
            $data[ 'comment' ][] = Message::BetweenCountModel($s, $e, [ 'p_user_id' => $user->id, 'is_show' => 4 ]);
        }
        return data($data);
    }

    /**
     * 获取文章筛选条件
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleTableService( $request )
    {
        $user    = $this->getCommon()->UserCommonService();
        $where   = function ( $query ) use ( $user, $request ) {
            $query->where('user_id', $user->id);
            if ( $request->filled('category') ) $query->where('category_id', $request->input('category'));
            if ( $request->filled('parent') ) $query->where('parent_id', $request->input('parent'));
            if ( $request->filled('status') ) $query->where('status', $request->input('status'));
            if ( $request->filled('is_show') ) $query->where('is_show', $request->input('is_show'));
            if ( $request->filled('root') ) $query->where('root', $request->input('root'));
            if ( $request->filled('title') ) $query->where('title', $request->input('title'));
            if ( $request->filled('created_at') ) {
                $time       = $request->input('created_at');
                $start_time = $time[ 0 ];
                $end_time   = $time[ 1 ];
                $query->whereBetween('created_at', [ $start_time, $end_time ]);
            }
            $query->where('static', 1);
        };
        $with    = [
            'category'     => function ( $query ) {
                $query->select('id', 'name');
            },
            'parent'       => function ( $query ) {
                $query->select('id', 'name');
            },
            'articleLabel' => function ( $query ) {
                $query->select('id', 'name', 'color');
            },
        ];
        $select  = [
            'id', 'user_id', 'title', 'browse', 'category_id', 'share', 'like', 'is_show', 'step', 'comment',
            'parent_id', 'updated_at', 'root', 'static', 'status', 'fail', 'is',
        ];
        $article = Article::PaginateModel($where, $with, $select, $request->input('limit'));
        return data($article);
    }

    /**
     * 创建文章
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleCreateService( $request )
    {
        $user      = $this->getCommon()->UserCommonService();
        $validator = $this->getBlogValidator()->BlogArticleValidator($request);
        if ( $validator->first() ) return message($validator->first());
        $data[ 'user_id' ]     = $user->id;
        $data[ 'title' ]       = $request->input('title');
        $data[ 'category_id' ] = $request->input('category_id');
        $data[ 'pic' ]         = $request->input('pic');
        $data[ 'parent_id' ]   = $request->input('parent_id', 0);
        $data[ 'root' ]        = $request->input('root') == TRUE ? 2 : 1;
        $data[ 'is' ]          = $request->input('is') == TRUE ? 1 : 2;
        $data[ 'status' ]      = $request->input('status');
        DB::transaction(function () use ( $request, $data ) {
            $article = Article::CreateModel($data);
            $article->articleLabel()->sync($request->input('tag'));
            unset($data);
            $data[ 'text' ]     = $request->input('text');
            $data[ 'html' ]     = $request->input('html');
            $data[ 'markdown' ] = $request->input('markdown');
            $data[ 'intro' ]    = $request->input('intro');
            $article->content()->create($data);
        });
        return data();
    }

    /**
     * 获取文章详情
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleShowService( $request )
    {
        $user                  = $this->getCommon()->UserCommonService();
        $with                  = [
            'file'    => function ( $query ) {
                $query->select('id', 'url');
            },
            'content' => function ( $query ) {
                $query->select('article_id', 'text', 'markdown', 'html', 'intro');
            },
        ];
        $where                 = function ( $query ) use ( $user, $request ) {
            $query->where('user_id', $user->id);
            $query->where('id', $request->input('id'));
        };
        $select                = [ 'id', 'user_id', 'category_id', 'parent_id', 'title', 'root', 'pic', 'is' ];
        $article               = Article::FirstModel($where, $with, $select);
        $article->articleLabel = $article->articleLabel()->pluck('id');
        return data($article);
    }

    /**
     * 修改文章
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleEditService( $request )
    {
        $user      = $this->getCommon()->UserCommonService();
        $validator = $this->getBlogValidator()->BlogArticleValidator($request);
        if ( $validator->first() ) return message($validator->first());
        $where                 = function ( $query ) use ( $request, $user ) {
            $query->where('id', $request->input('id'));
            $query->where('user_id', $user->id);
        };
        $data[ 'user_id' ]     = $user->id;
        $data[ 'title' ]       = $request->input('title');
        $data[ 'category_id' ] = $request->input('category_id');
        $data[ 'pic' ]         = $request->input('pic');
        $data[ 'parent_id' ]   = $request->input('parent_id', 0);
        $data[ 'root' ]        = $request->input('root') == TRUE ? 2 : 1;
        $data[ 'is' ]          = $request->input('is') == TRUE ? 1 : 2;
        $data[ 'status' ]      = $request->input('status');
        DB::transaction(function () use ( $request, $data, $where ) {
            $article = Article::FirstModel($where);
            $article->update($data);
            $article->articleLabel()->sync($request->input('tag'));
            unset($data);
            $data[ 'text' ]     = $request->input('text');
            $data[ 'html' ]     = $request->input('html');
            $data[ 'markdown' ] = $request->input('markdown');
            $data[ 'intro' ]    = $request->input('intro');
            $article->content()->update($data);
        });
        return data();
    }

    /**
     * 修改文章状态
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ArticleIsShowService( $request )
    {
        $user          = $this->getCommon()->UserCommonService();
        $where         = function ( $query ) use ( $request, $user ) {
            $query->where('id', $request->input('id'));
            $query->where('user_id', $user->id);
        };
        $key           = $request->input('key');
        $article       = Article::FirstModel($where, [], [ 'id', $key ]);
        $article->$key = $request->input('value') == 1 ? 1 : 2;
        $article->save();
        return data(NULL, $this->getErrorCode()::message(210));
    }
}
